<template>
  <div class="app-container">
    <el-form :model="queryParams" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据日期" prop="documentDate" label-width="100px">
        <el-date-picker v-model="queryParams.documentDate" type="daterange" range-separator="到"
                        value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item label="收费项目" prop="chargeType" label-width="100px">
        <!--        <el-input v-model="queryParams.reason" placeholder="请输入名称" clearable @keyup.enter="handleQuery"/>-->
        <el-select v-model="queryParams.chargeType" placeholder="请选择类别" clearable>
          <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.showvalue"
                     :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Switch" :disabled="multiple" @click="makeVoucher()">
          凭证制作
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="gridData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="documentDate" label="单据日期" algin="center"/>
      <el-table-column prop="documentCode" label="单据编码" show-overflow-tooltip algin="center"/>
      <el-table-column prop="documentName" label="单据名称" algin="center"/>
      <el-table-column prop="propertyCode" label="资产编码" algin="center"/>
      <el-table-column prop="propertyName" label="资产名称" algin="center"/>
      <el-table-column prop="corpName" width="200px" label="所属公司" algin="center"/>
      <el-table-column prop="feeType" label="收费项目" algin="center" :formatter="formatter"/>
      <el-table-column prop="abstractStr" label="摘要" width="400px" algin="center"/>
      <el-table-column prop="peice" label="金额" algin="center"/>
    </el-table>
    <el-pagination :total="total" v-model:current-page="listQuery.page" v-model:page-size="listQuery.pageSize"
                   @current-change="getList"/>

    <el-dialog title="凭证制作" v-model="open" width="1000px">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体账簿" prop="pk_glorgbook">
              <el-select v-model="form.pk_glorgbook" filterable placeholder="请选择主体账簿" style="width:100%"
                         @change="getSubject(form.pk_glorgbook)">
                <el-option v-for="item in bookOptions" :key="item.glorgbookname" :label="item.glorgbookname"
                           :value="item.glorgbookname"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="凭证类别" prop="pk_vouchertype">
              <el-select v-model="form.pk_vouchertype" filterable style="width:100%" placeholder="请选择凭证类别">
                <el-option v-for="item in classOptions" :key="item.name" :label="item.name"
                           :value="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="制单人" prop="pk_prepared">
              <el-select v-model="form.pk_prepared" filterable style="width:100%" placeholder="请选择制单人">
                <el-option v-for="item in makerOptions" :key="item.userName" :label="item.userName"
                           :value="item.userName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单日期" prop="prepareddate">
              <el-date-picker
                  v-model="form.prepareddate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style="width:100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="贷方科目编码" prop="dai_accsubj">
              <el-select v-model="form.dai_accsubj" filterable placeholder="请选择贷方科目编码" style="width:100%"
                         @change="getAssis(0,form.dai_accsubj,form.pk_glorgbook)">
                <el-option v-for="item in subOptions" :key="item.dispname" :label="item.dispname"
                           :value="item.dispname"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借方科目编码" prop="jei_accsubj">
              <el-select v-model="form.jei_accsubj" filterable placeholder="请选择借方科目编码" style="width:100%"
                         @change="getAssis(1,form.jei_accsubj,form.pk_glorgbook)">
                <el-option v-for="item in subOptions" :key="item.dispname" :label="item.dispname"
                           :value="item.dispname"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="贷方辅助核算" prop="daiCode">
              <el-input v-model="form.daiCode" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" clearable
                        @click="getAssis(0,form.dai_accsubj,form.pk_glorgbook)"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借方辅助核算" prop="jieCode">
              <el-input v-model="form.jieCode" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" clearable
                        @click="getAssis(1,form.jei_accsubj,form.pk_glorgbook)"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="现金流量" prop="pk_cashflow">
              <el-select v-model="form.pk_cashflow" filterable placeholder="请选择现金流量" style="width:100%"
                         clearable>
                <el-option v-for="item in cashOptions" :key="item.cfitemname" :label="item.cfitemname"
                           :value="item.cfitemname"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
          <el-table :data="selectionList">
            <el-table-column prop="abstractStr" label="摘要" width="400px" algin="center"/>
            <el-table-column prop="peice" label="金额" algin="center"/>
          </el-table>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">生 成</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="辅助核算列表" v-model="look">
      <el-table :data="borrowAssisOptions" style="width: 100%" border stripe>
        <el-table-column prop="studentCode" label="核算类型名称"></el-table-column>
        <el-table-column label="核算内容">
          <template v-slot="scope">
            <el-select v-model="scope.row.studentName" @focus="getDatalist(scope.row)" placeholder="请选择核算内容"
                       filterable allow-create>
              <el-option v-for="item in contentOptions" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="look=false">取 消</el-button>
          <el-button type="primary" @click="submitConfig">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name: "ImportLog",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      look: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      selectionList: [],
      gridData: [],
      listQuery: {
        page: 1,
        pageSize: 10,
      },
      queryParams: {
        chargeType: null,
        documentDate: null
      },
      total: 0,
      typeOptions: [],
      classOptions: [{name: "记账"}, {name: "专项"}],
      bookOptions: [],
      cashOptions: [],
      makerOptions: [],
      subOptions: [],
      borrowAssisOptions: [],
      loanAssisOptions: [],
      assisOptions: [],
      borrowContentOptions: [],
      loanContentOptions: [],
      contentOptions: [],
      open: false,
      // 表单参数
      form: {
        borrowContent: null,
        daiCode: null,
        dai_accsubj: null,
        explanation: null,
        id: null,
        jei_accsubj: null,
        jieCode: null,
        laonContent: null,
        pk_accsubj: null,
        pk_cashflow: null,
        pk_glorgbook: null,
        pk_prepared: null,
        pk_vouchertype: null,
        details: []
      },
      detail: [],
      rules: {
        pk_glorgbook: [{required: true, message: "请选择主体账簿", trigger: "blur"}],
        pk_vouchertype: [{required: true, message: "请选择凭证类别", trigger: "blur"}],
        pk_prepared: [{required: true, message: "请选择制单人", trigger: "blur"}],
        dai_accsubj: [{required: true, message: "请选择贷方科目编码", trigger: "blur"}],
        jei_accsubj: [{required: true, message: "请选择借方科目编码", trigger: "blur"}],
      },
      // 选中的行
      selected: null,
      projectJbrUserlist: [], // 处理人员数据
      nodeidlist: [], // 所有流程节点Id
      selectedUserlist: [], // 被选中的处理人员id数组
    }
  },
  watch: {},
  computed: {
    timeDefault() {
      var date = new Date();
      var s1 = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate());
      return s1;
    }
  },
  //页面加载时候，在mounted中进行赋值
  mounted() {
    // 初始化查询，默认为前一天
    this.form.prepareddate = this.timeDefault;
  },
  created() {
    this.getChargeType();
    this.getList();
  },
  methods: {
    // select下拉框获取焦点的时候查询id对应的下拉框数据源
    async getDatalist(row) {
      let data = {
        bdname: row.studentCode,
        subjcode: this.selected.subjcode,
        pkglorgbook: this.selected.pkglorgbook
      }
      request.post('/bdBdinfo/getClass', data).then(res => {
        this.look = true
        this.contentOptions = res.data
      })
    },
    // 提交流程配置接口
    async submitConfig() {
      if (this.selected.type == 1) {
        let jieCode = '';
        this.borrowAssisOptions.forEach(function (item) {
          if (jieCode == '') {
            jieCode = (item.studentCode + '/' + item.studentName)
          } else {
            jieCode += ('/' + item.studentCode + '/' + item.studentName)
          }
        })
        if (jieCode.indexOf(null) > 0) {
          ElMessage({
            showClose: true,
            message: '核算内容不能为空',
            type: 'error',
          })
        } else {
          this.form.jieCode = jieCode
          this.look = false
        }
      } else if (this.selected.type == 0) {
        let daiCode = '';
        this.borrowAssisOptions.forEach(function (item) {
          if (daiCode == '') {
            daiCode = (item.studentCode + '/' + item.studentName)
          } else {
            daiCode += ('/' + item.studentCode + '/' + item.studentName)
          }
        })
        // 如果daiCode不包含null值，则将daiCode拼接成字符串且将look设置为false
        if (daiCode.indexOf(null) > 0) {
          ElMessage({
            showClose: true,
            message: '核算内容不能为空',
            type: 'error',
          })
        } else {
          this.form.daiCode = daiCode
          this.look = false
        }
      }
    },

    formatter(row) {
      return this.selectDictLabel(row.feeType);
    },
    getSubject(name) {
      let data = {
        name: name
      }
      request.post('/bdAccsubj/getByPk', data).then(res => {
        this.subOptions = res.data
        this.subOptions.forEach(function (item) {
          item.dispname = item.dispname.replaceAll("\\", "-")
        })
      })
    },
    getAssis(type, subjcode, pkglorgbook) {
      this.borrowAssisOptions = []
      if (subjcode == null) {
        ElMessage({
          showClose: true,
          message: '请选择会计科目',
          type: 'error',
        })
        return
      }
      if (pkglorgbook == null) {
        ElMessage({
          showClose: true,
          message: '请选择主体账簿',
          type: 'error',
        })
        return
      }
      let data = {
        subjcode: subjcode,
        pkglorgbook: pkglorgbook
      }
      request.post('/bdBdinfo/getList', data).then(res => {
        this.borrowAssisOptions = res.data
        this.borrowAssisOptions.forEach(function (item) {
          item.id = item.bdcode
          item.studentCode = item.bdcode + '-' + item.bdname
          item.studentName = null;
        })
        this.look = true
      })
      this.selected = {
        type: type,
        subjcode: subjcode,
        pkglorgbook: pkglorgbook
      }
    },

    // 回显数据字典
    selectDictLabel(value) {
      const datas = this.typeOptions;
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].id == ('' + value)) {
          actions.push(datas[key].showvalue);
          return true;
        }
      })
      return actions.join('');
    },
    getChargeType() {
      request.get('/formmain0125/getChargeType').then(res => {
        this.typeOptions = res.data;
      });
    },
    getList() {
      this.loading = true;
      let data = {
        ...this.listQuery,
        ...this.queryParams
      }
      request.post('/formmain0125/getList', data).then(res => {
        this.loading = false;
        this.total = res.data.total
        this.gridData = res.data.records;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.listQuery.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery.page = 1;
      this.queryParams.reason = null;
      this.queryParams.chargeType = null;
      this.selectionList[0]
      this.form = {
        borrowContent: null,
        daiCode: null,
        dai_accsubj: null,
        explanation: null,
        id: null,
        jei_accsubj: null,
        jieCode: null,
        laonContent: null,
        pk_accsubj: null,
        pk_cashflow: null,
        pk_glorgbook: null,
        pk_prepared: null,
        pk_vouchertype: null,
        details: []
      }
      this.handleQuery();
    },
    makeVoucher() {
      this.selectionList.forEach(item => {
        if (item.id == null) {
          ElMessage({
            showClose: true,
            message: '选中该数据的id值为空，请联系管理员',
            type: 'error',
          })
          return
        }
        if (item.abstractStr == null) {
          ElMessage({
            showClose: true,
            message: '选中该的数据摘要值不能为空',
            type: 'error',
          })
          return
        }
        if (item.peice == null) {
          ElMessage({
            showClose: true,
            message: '选中数据的金额不能为空',
            type: 'error',
          })
          return
        }
      })
      // 摘要 金额
      this.form.pk_vouchertype = this.classOptions[0].name

      request.get('/bdGlorgbook/getList',).then(res => {
        this.bookOptions = res.data
      })
      request.get('/bdCashflow/getList').then(res => {
        this.cashOptions = res.data
        this.cashOptions.forEach(function (item) {
          item.cfitemname = item.cfitemcode + '-' + item.cfitemname
        })
      })
      request.get('/smUser/getList').then(res => {
        this.makerOptions = res.data
      })
      this.open = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.resetQuery();
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.prepareddate == 0) {
        ElMessage({
          showClose: true,
          message: '请选择制单日期',
          type: 'error',
        })
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.selectionList.forEach(item => {
            let detail = {
              id: null,
              daiCode: null,
              dai_accsubj: null,
              explanation: null,
              pk_accsubj: null,
              jieCode: null,
              jei_accsubj: null,
            }
            detail.id = item.id
            detail.daiCode = this.form.daiCode
            detail.dai_accsubj = this.form.dai_accsubj
            detail.explanation = item.abstractStr
            detail.pk_accsubj = item.peice
            detail.jieCode = this.form.jieCode
            detail.jei_accsubj = this.form.jei_accsubj
            this.form.details.push(detail)
          })
          if (this.form.daiCode.indexOf(null) > 0 || this.form.jieCode.indexOf(null) > 0) {
            ElMessage({
              showClose: true,
              message: '核算内容不能为空',
              type: 'error',
            })
          } else {
            axios({
              url: '/api/glVoucher/save',
              method: 'post',
              headers: {'Content-Type': 'application/json'},
              data: this.form
            }).then(res => {
              if (res.data.success) {
                ElMessage({
                  showClose: true,
                  message: res.data.data,
                  type: 'success',
                })
              } else {
                ElMessage({
                  showClose: true,
                  message: res.data.data,
                  type: 'error',
                })
              }
              this.open = false;
              this.resetQuery();
            }).catch(error => {
              console.log(error)
              this.open = false;
              this.resetQuery();
              ElMessage({
                showClose: true,
                message: '生成失败！请联系管理员',
                type: 'error',
              });
            })
            this.open = false;
          }
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectionList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
  }
}
</script>

<style scoped>

.mb8 {
  margin-bottom: 20px;
}

.app-container {
  margin: 0;
  height: 96%;
  padding: 2px 10px 10px;
  background-color: #FFFFFF;
}

</style>